package com.example.gouwu2;

import java.util.ArrayList;
import java.util.List;


public class CartManager {
    //  volatile确保多线程可见性
    private static volatile CartManager instance;

    // 购物车商品列表 - 存储CartItem对象
    private List<CartItem> cartItems = new ArrayList<>();

    private CartManager() {}

    //获取购物车商品内容
    public static synchronized CartManager getInstance() {

        if (instance == null) {
            synchronized (CartManager.class) {
                if (instance == null) {
                    instance = new CartManager();
                }
            }
        }
        return instance;
    }

    // 添加商品到购物车

    public void addItem(CartItem item) {
        cartItems.add(item);
    }

    public List<CartItem> getCartItems() {
        // 创建新列表返回
        return new ArrayList<>(cartItems);
    }

    //清空购物车
    public void clearCart() {
        cartItems.clear();
    }

    public static class CartItem {

        private String title;

        private String price;

        private int imageRes;

        // 构造函数
        public CartItem(String title, String price, int imageRes) {
            this.title = title;
            this.price = price;
            this.imageRes = imageRes;
        }

        // --- Getter方法 ---
        public String getTitle() {
            return title;
        }

        public String getPrice() {
            return price;
        }

        public int getImageRes() {
            return imageRes;
        }
    }
}